package com.example.newbilityblog.admin.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.newbilityblog.admin.config.OSSConfig;
import com.example.newbilityblog.common.utils.Result;
import com.example.newbilityblog.common.utils.ResultGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;

@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class UploadController {
    private final OSSConfig ossConfig;

    @ResponseBody
    @PostMapping("/upload/file")
    public Result<String> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException, URISyntaxException {
        var fileName = file.getOriginalFilename();
        String completePath = "newbility-blog/images/test/" + fileName;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        ossClient.putObject("newbility-blog", completePath, file.getInputStream());
        ossClient.shutdown();
        var result = ResultGenerator.genSuccessResult();
        result.setData("https://newbility-blog.oss-cn-beijing.aliyuncs.com/" + completePath);
        return result;
    }
}
